package service

import (
	"context"
	"github.com/micro/go-micro/v2/errors"
	"micro-grpc-server/services/user/internal/models"
	pb "micro-grpc-server/services/user/proto"
	wechat "micro-grpc-server/services/wechat/proto"
)

// 账号注册
func (s *UserService) Register(ctx context.Context, rq *pb.RegisterRequest, resp *pb.TokenResponse) (err error) {
	if rq.Password != rq.PasswordConfirm {
		return errors.BadRequest(s.conf.ServerName, "两次密码输入不一致")
	}
	var identity *models.Identity
	if identity, err = s.dao.RegisterNormal(rq); err != nil {
		return err
	}

	return s.assemblyToken(identity, resp)
}

// 密码登录
func (s *UserService) LoginByPassword(ctx context.Context, rq *pb.LoginRequest, resp *pb.TokenResponse) (err error) {
	var identity *models.Identity
	if identity, err = s.dao.LoginByPassword(rq); err != nil {
		return err
	}

	return s.assemblyToken(identity, resp)
}

// 微信登录
func (s *UserService) LoginByWechat(ctx context.Context, rq *wechat.WechatUserInfoRequest, resp *pb.TokenResponse) (err error) {
	wechatUserInfo, err := s.wechatCli.WechatUserInfo(ctx, rq)
	if err != nil {
		return
	}

	var identity *models.Identity
	// 通过openid就找到用户了 直接返回
	if identity, _ = s.dao.FindUserByOpenid(wechatUserInfo.OpenId, wechatUserInfo.Scenario); identity != nil {
		return s.assemblyToken(identity, resp)
	}
	// 没有拿到用户信息
	if len(wechatUserInfo.UnionId) == 0 {
		return errors.BadRequest(s.conf.ServerName, "未注册用户")
	}
	// 通过微信数据注册用户
	if identity, err = s.dao.RegisterWechat(wechatUserInfo); err != nil {
		return err
	}

	return s.assemblyToken(identity, resp)
}

// 组装token数据
func (s *UserService) assemblyToken(user *models.Identity, resp *pb.TokenResponse) (err error) {
	var token *models.Token
	if token, resp.AccessToken, err = s.dao.GenerateToken(user); err != nil {
		return err
	}
	resp.TimeExpired = token.TimeExpired
	resp.RefreshToken = token.RefreshToken

	return nil
}
